<template>
  <div>
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <span class="card-title">{{ title }}</span>
        <el-button
          style="float: right"
          size="mini"
          type="primary"
          @click="() => handleSave(false)"
          >保存</el-button
        >
      </div>
      <div class="text item">
        <el-form
          :model="template"
          :rules="rules"
          ref="templateForm"
          label-width="100px"
          label-position="left"
        >
          <el-form-item label="名称" prop="name">
            <el-input v-model="template.name"></el-input>
          </el-form-item>
          <el-form-item label="模块" prop="moduleCode">
            <module-select v-model="template.moduleCode"></module-select>
          </el-form-item>
          <el-form-item label="模板文件" prop="templateFileId">
            <el-link type="primary" @click="handleDownloadFile">{{
              template.templateFileName
            }}</el-link>
            <el-upload
              class="upload-demo"
              :action="fileUploadUrl"
              :on-success="handleFileSucess"
              :on-error="handleFileError"
              ref="templateFile"
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>
<script>
import {
  getPrintTemplate,
  addPrintTemplate,
  updatePrintTemplate,
} from "@/api/print";
import { downloadFile } from "@/api/file";
import moduleSelect from "@/components/Select/moduleSelect.vue";
export default {
  components: {
    moduleSelect,
  },
  data() {
    return {
      template: {
        id: "",
        name: "",
        moduleCode: "",
        templateFileId: null,
        templateFileName: "",
        imageFileId: null,
      },
      rules: {
        moduleCode: [
          { required: true, message: "请填写模块", trigger: "blur" },
        ],
        name: [{ required: true, message: "请填写名称", trigger: "blur" }],
        templateFileId: [
          { required: true, message: "请上传模板文件", trigger: "blur" },
        ],
      },
      title: "",
      baseUrl: "",
    };
  },
  methods: {
    getData() {
      if (!this.id) return;
      getPrintTemplate(this.id).then((res) => {
        this.template = res || {};
      });
    },
    handleSave() {
      this.$refs.templateForm.validate((valid) => {
        if (valid) {
          this.saveData();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    saveData() {
      if (!this.id) {
        addPrintTemplate(this.template).then((res) => {
          if (!res) return;
          this.$notify({
            title: "成功",
            message: "保存成功",
            type: "success",
            position: "bottom-right",
          });
          this.$emit("refresh", res);
        });
      } else {
        updatePrintTemplate(this.template).then((res) => {
          if (!res) return;
          this.$notify({
            title: "成功",
            message: "保存成功",
            type: "success",
            position: "bottom-right",
          });
          this.$emit("refresh", res);
        });
      }
    },
    handleFileSucess(res) {
      if (!res) {
        this.$notify({
          title: "失败",
          message: "文件上传失败",
          type: "error",
          position: "bottom-right",
        });
        return;
      }
      this.$refs.templateFile.clearFiles();

      this.template.templateFileId = res.id;
      this.template.templateFileName = res.fileName + res.fileExtension;
    },
    handleFileError(err) {
      console.log("err", err);
      err = err["message"];
      let res = JSON.parse(err); //转对象

      let message =
        res && res.error && res.error.message
          ? res.error.message
          : "文件上传失败";
      this.$notify({
        title: "失败",
        message: message,
        type: "error",
        position: "bottom-right",
      });
    },
    handleDownloadFile() {
      let fileId = this.template.templateFileId;
      let name = this.template.templateFileName;
      let contentType = this.template.templateFileContentType;
      downloadFile({ id: fileId }).then((res) => {
        let blob = new Blob([res], {
          type: contentType,
        });
        let link = document.createElement("a");
        link.href = window.URL.createObjectURL(blob);
        link.download = name;
        link.click();

        window.URL.revokeObjectURL(link.href);
      });
    },
  },
  mounted() {
    this.baseUrl = process.env.VUE_APP_BASE_API;
    this.title = this.id ? "编辑" : "新增";
    this.getData();
  },
  computed: {
    fileUploadUrl() {
      return this.baseUrl + "api/v1/files";
    },
  },
  props: {
    id: {
      type: String,
      default: "",
    },
  },
};
</script>
<style scoped></style>
